<?php

namespace app\admin\controller;

use app\admin\model\Rule as RuleModel;
use app\admin\validate\Rule as RuleV;
use think\facade\View;

class Rule extends Base
{
    /**
     * 节点列表
     */
    public function index()
    {
        // echo addon_url('user/admin.user/index');exit;
        $list = RuleModel::order('sort desc,id asc')->select();
        $list = children_name($list->toArray(), 'name');
        return View::fetch('', ['list' => $list]);
    }

    /**
     * 添加节点
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try {
                validate(RuleV::class)->check($this->post);
                (new RuleModel)->replace()->cache('admin_menu_list')->save($this->post);
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '添加失败');
            }
            return $this->success('添加成功', 'index');
        }
        $where = [
            ['status', '=', 1],
        ];
        $list = RuleModel::where($where)->order('sort desc')->select();

        return View::fetch('', ['parent_list' => children_name($list->toArray(), 'name')]);
    }

    /**
     * 修改节点
     */
    public function edit()
    {
        $info = RuleModel::find($this->get['id']);
        $info->hidden(['create_time','update_time']);
        if ($this->request->isAjax()) {
            try {
                validate(RuleV::class)->check($this->post);
                $info->replace()->cache('admin_menu_list')->save($this->post);
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '修改失败');
            }
            return $this->success('修改成功', 'index');
        }
        $where = [
            ['status', '=', 1]
        ];
        $list = RuleModel::where($where)->order('sort desc')->select();
        return View::fetch('', ['parent_list' => children_name($list->toArray(), 'name'), 'info' => $info]);
    }

    /**
     * 删除节点
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $info = RuleModel::where($this->post)->find();
            try {
                $info->cache('admin_menu_list')->delete();
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '删除失败');
            }
            return $this->success('删除成功', 'index');
        }
    }
}
